package com.lenovo.leos.letools.utils;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import android.content.Context;
/**
 * operate cookie
 * @author cys
 *
 */
public class CookieStore {

	private static final String filename="cookieFile.temp";
	
	/**
	 * 从返回的响应头中（包括响应行）筛选出Cookie的集合
	 * @param maps
	 * @return
	 */
	public static List<String> filterCookies(Map<String, List<String>> maps){
		if(maps==null){
			return null;
		}
		/*
		 * 服务器端返回的一条完整的cookie信息
		 * AUTH_PRO=1084fe7b69e97ab19834cd00000000000000; path=/; domain=.vips100.com
		 */
		List<String> allCookies=new ArrayList<String>();
		/*
		 * 而客户端传递给服务器端的cookie信息，一般只需要最前面的这一部分
		 * AUTH_PRO=1084fe7b69e97ab19834cd00000000000000
		 */
		List<String> cookies=new ArrayList<String>();
		
		Set<Map.Entry<String, List<String>>> entrys = maps.entrySet();
		for (Map.Entry<String, List<String>> entry : entrys) {
			
			String cookieKey = entry.getKey();
			if ("Set-Cookie".equalsIgnoreCase(cookieKey)) {// 得到头中的cookie信息集合
				allCookies=entry.getValue();
				break;
			}
		}
		for(String allcookie : allCookies ){
			/*
			 * 截取cookie信息的第一部分  
			 * 如：AUTH_PRO=1084fe7b69e97ab19834cd00000000000000
			 */
			cookies.add(allcookie.substring(0, allcookie.indexOf(";")));
		}
		return cookies;
	}
	
	/**
	 * add cookie
	 * @param context 
	 * @param cookieVal
	 */

	public static void addCookie(Context context ,String cookieVal){
		try {
			FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE);
			fos.write(cookieVal.getBytes());
			fos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * get cookie
	 * @param context
	 * @return
	 */
	public static String getCookie(Context context){
		String cookieVal=null;
		try {
			FileInputStream fos = context.openFileInput(filename);
			byte[] buf = new byte[1024];
			fos.read(buf);
			cookieVal = new String(buf,0,buf.length);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return cookieVal==null?null:cookieVal.trim();
	}
}
